import {
  getLayerSourceByType,
  getLayerSourceCommunityLiveRange,
  getLayerSourceCommunityRegion,
  getLayerSourceByCatalogId,
  getSpecialRegionArea
} from '@api/question'
import {
  communityTree,
  regionTree,
  residenceTree,
  streetTree,
} from '@/hooks/catalogTree'
import { closeLoading, showLoading } from '@/utils/loading'
import { useOldBuilding } from '@/hooks/useOldBuilding'
import { isObject } from '@/utils/radash'
import { Message } from 'element-ui'
import mapboxgl, { LngLat } from 'mapbox-gl'
import * as turf from '@turf/turf'
import emitter from '@/utils/event-bus'
import { getLayerStyleByPkid, applyLayerStyle, getDefaultStyleByType } from '@/hooks/mapRightTree'

export const layersIdPaths = {}

const markerCache = new Map()

const buildingLayerCache = new Map()

let highlightGeoJsonLayerId = 'highlight-geojson';

let highlightMarkerList = [];
let customPointsCache = new Map(); // 新增：自定义点位缓存

const getPaths = (tree, targetObj, parentId) => {
  if (!Array.isArray(tree)) return
  tree.forEach((item) => {
    if (item.children && item.children.length > 0) {
      targetObj[item.id] = {
        id: item.children.map((child) => child.id),
        color: item.color,
        name: item.name,
        icon: item.icon,
      }
      getPaths(item.children, targetObj, item.id)
    } else {
      targetObj[item.id] = {
        id: parentId + '.' + item.id,
        color: item.color,
        name: item.name,
        icon: item.icon,
      }
    }
  })
}
getPaths(communityTree, layersIdPaths)
getPaths(streetTree, layersIdPaths)
getPaths(residenceTree, layersIdPaths)
getPaths(regionTree, layersIdPaths)

const oldBuildingHelper = useOldBuilding()

export function useMapData() {
  let map = null
  let layerManager = null

  let layerSource = {}

  let onBuildingLayerAdded = null
  let onBuildingLayerRemoved = null
  let onMarkerClick = null
  let onLayerLoaded = null

  let activeMarker = null

  let isMarkerClick = false

  const setBuildingCallback = (callback) => {
    onBuildingLayerAdded = callback
  }

  const setBuildingRemovedCallback = (callback) => {
    onBuildingLayerRemoved = callback
  }

  const setMarkerClickCallback = (callback) => {
    onMarkerClick = callback
  }

  const setLayerLoadedCallback = (callback) => {
    onLayerLoaded = callback
  }

  const getRegionSpecialSource = async (sourceKey, key, params) => {
    if (!layerSource[sourceKey]) {
      try {
        const res = await getSpecialRegionArea(sourceKey, {
          ...params,
          isWgs: true,
        })
        layerSource[sourceKey] = res.success ? res.data : {}
      } catch (e) {
        console.error(e)
        layerSource[sourceKey] = {}
      }
    }

    let source = layerSource[sourceKey]
    if (key === 'IdleRange' && typeof source === 'object') {
      const combineFeatures = (ranges) =>
        ranges
          .map((range) =>
            JSON.parse(range[0] || '{"features":[]}').features.map(
              (feature) => {
                return {
                  ...feature,
                  properties: {
                    ...feature.properties,
                    templateType: range[1],
                  },
                }
              }
            )
          )
          .flat()
      const features = combineFeatures([
        [source.liveIdleRange, 'region-live'],
        [source.businessIdleRange, 'region-business'],
        [source.industryIdleRange, 'region-industry'],
        [source.historyCultureIdleRange, 'region-culture'],
      ])

      source.IdleRange = JSON.stringify({ type: 'FeatureCollection', features })
    }
    return typeof source !== 'object' ? source : source[key] || []
  }

  const getLayerSource = async (layerId, params) => {
    const path = layersIdPaths[layerId].id
    if (!path.includes('.')) {
      return getOrFetchSource(path, params)
    }

    if (path.includes('communityRegion')) {
      return getOrFetchSource(path, params, getLayerSourceCommunityRegion)
    }
    if (path.includes('warning')) {
      if (!layerSource[path]) {
        layerSource[path] = oldBuildingHelper.getPointsServiceSource({
          ...params,
          regionId: '',
          streetId: '',
          communityId: '',
        })
      }
      return layerSource[path]
    }

    let [sourceKey, key] = path.split('.')
    if (sourceKey === 'residenceRegion') sourceKey = 'residence'

    const specialRegionKeys = [
      'IdleRange',
      'ManageRange',
      'businessStreetRange',
      'businessGreenRange',
      'businessUpdateRange',
    ]
    if (specialRegionKeys.includes(key)) {
      return await getRegionSpecialSource(sourceKey + 'special', key, params)
    }

    const regionCommunityKeys = ['communityLiveVacant', 'communityLiveManage']
    if (regionCommunityKeys.includes(key)) {
      return await getOrFetchSource(
        sourceKey + 'community',
        params,
        getLayerSourceCommunityLiveRange,
        key
      )
    }

    return getOrFetchSource(sourceKey, params, getLayerSourceByType, key)
  }

  const getOrFetchSource = async (
    key,
    params,
    fetcher = getLayerSourceByType,
    subKey
  ) => {
    if (!layerSource[key]) {
      try {
        const res = await fetcher(key, { ...params, isWgs: true })
        layerSource[key] = res.success ? res.data : subKey ? {} : []
      } catch (e) {
        console.error(e)
        layerSource[key] = subKey ? {} : []
      }
    }

    const source = layerSource[key]
    return subKey
      ? typeof source !== 'object'
        ? source
        : source[subKey] || []
      : source
  }

  const init = (_map, _layerManager) => {
    map = _map
    // console.log(_layerManager)
    layerManager = _layerManager.get('one-map')
  }

  const addLayerByCatalogId = async (catalogId, params) => {
    // const paths = layersIdPaths[catalogId].id
    // console.log(paths)
    // if (Array.isArray(paths)) {
    //   // 这种情况是选择下面全部，但是这里已经是遍历了，就不用处理了
    // } else {
      // console.log(catalogId)
      await addLayer(catalogId, params)
    // }
  }

  const removeLayerByCatalogId = async (catalogId) => {
    await checkAndRemoveBuildingLayer(catalogId)
    removeLayer(catalogId)
  }

  const checkAndRemoveBuildingLayer = async (catalogId) => {
    // 如果缓存中有这个图层，说明它包含建筑物数据
    if (buildingLayerCache.has(catalogId)) {
      const removedBuildingIds = buildingLayerCache.get(catalogId)
      // console.log('在缓存中找到建筑物图层，建筑物ID:', removedBuildingIds)
  
      buildingLayerCache.delete(catalogId)
  
      if (typeof onBuildingLayerRemoved === 'function') {
        // console.log('调用建筑物图层删除回调')
        onBuildingLayerRemoved({
          layerId: catalogId,
          buildingIds: removedBuildingIds
        })
      }
      return
    }

    try {
      const info = {
        templateId: catalogId,
      }
      const res = await getLayerSourceByCatalogId(info)
      
      if (res.data && res.data.length > 0) {
        const hasBuildingData = res.data.some(item => 
          item.buildingPointsResult && item.buildingPointsResult.trim() !== ''
        )
        
        if (hasBuildingData && typeof onBuildingLayerRemoved === 'function') {
          onBuildingLayerRemoved({
            layerId: catalogId,
            buildingIds: []
          })
        }
      }
    } catch (error) {
      console.error('检查建筑物图层时出错:', error)
    }
  }

  const pointIds = [
    'synthesizeStation',
    'cultureRoom',
    'safeStation',
    'communityElder',
    'communityDinner',
    'kindergarten',
    'nursery',
    'manageHouse',
    'embeddedService',
    'resourceBusinessBuild',
    'historyBuild',
    'warning',
  ]

  const lineIds = ['parkingProblemRoad', 'updateRoad']

  const getLayerStyle = (layerId) => {
    // 优先使用配置文件中的样式
    const styleConfig = getLayerStyleByPkid(layerId)
    if (styleConfig) {
      return {
        type: styleConfig.type,
        layout: styleConfig.style.layout || {},
        paint: styleConfig.style.paint || {},
      }
    }

    // 如果没有配置，使用原有逻辑
    // 根据layerId获取数据类型
    let type = 'fill'
    if (pointIds.includes(layerId)) {
      type = 'symbol'
    } else if (lineIds.includes(layerId)) {
      type = 'line'
    }
    // 随机获取颜色
    const color =
      '#' +
      ('000000' + Math.floor(Math.random() * 0xffffff).toString(16)).slice(-6)
    
    if (type === 'fill') {
      return {
        type: 'fill',
        layout: {},
        paint: {
          'fill-color': color,
          'fill-opacity': 0.2,
          'fill-outline-color': '#000000',
        },
      }
    } else if (type === 'circle') {
      return {
        type: 'circle',
        layout: {},
        paint: {
          'circle-color': color,
          'circle-radius': 6,
          'circle-opacity': 0.8,
        },
      }
    } else if (type === 'line') {
      return {
        type: 'line',
        layout: {},
        paint: {
          'line-color': color,
          'line-width': 2,
          'line-opacity': 0.8,
        },
      }
    } else if (type === 'symbol') {
      return {
        type: 'symbol',
        layout: {
          visibility: 'visible',
          'icon-image': layerId,
          'icon-size': 1,
        },
        paint: {},
      }
    }
  }

  const addLayer = async (layerId, params) => {
    showLoading()
    // 九龙坡老旧小区图层不传街道、社区、区域
    const info = {
      templateId: layerId,
      streetId: layerId === 'jlp_ljxqjz' ? '' : params.streetId,
      communityId: layerId === 'jlp_ljxqjz' ? '' : params.communityId,
      regionId: layerId === 'jlp_ljxqjz' ? '' : params.regionId,
    }
    const res = await getLayerSourceByCatalogId(info)
    const buildingPointsList = []

    res.data.forEach(item => {
      if (item.buildingPointsResult && item.buildingPointsResult.trim() !== '') {
        try {
          const parsed = JSON.parse(item.buildingPointsResult)
          buildingPointsList.push({
            data: parsed,
            pkid: item.pkid,
            templateId: item.templateId,
            name: item.name || '',
            status: item.status || ''
          })
        } catch (e) {
          console.log('e', e)
        }
      }
    })

    
    // 建筑物图层
    if (buildingPointsList.length > 0) {
      closeLoading()
      buildingLayerCache.set(layerId, buildingPointsList)
      // buildingLayerCache.add(layerId)
      // const buildingIds = buildingPointsList.flatMap(item => item.buildings || [])
      // const buildingIds = buildingPointsList.flatMap(item => 
      //   item.data.flatMap(d => d.buildings || [])
      // )
      // console.log('styleConfig----', )
      if (typeof onBuildingLayerAdded === 'function') {
        onBuildingLayerAdded(buildingPointsList, layerId, getLayerStyleByPkid(layerId))
      }
      closeLoading()
      return 
    } else {
      onBuildingLayerAdded([], layerId, getLayerStyleByPkid(layerId))
      closeLoading()
      // return
    }
    

    let geoJson
    if (Array.isArray(res.data)) {
      const features = res.data
        .filter((feature) => !!feature && feature.geoResult && feature.geoResult.trim() !== '')
        .map((feature) => {
          try {
            const parsedGeoResult = JSON.parse(feature.geoResult);
           
            return {
              type: 'Feature',
              geometry: parsedGeoResult.geometry,
              properties: {
                ...parsedGeoResult.properties,
                name: feature.name || '',
                pkid: feature.pkid, 
                templateId: feature.templateId,
              },
            };
          } catch (e) {
            return null;
          }
        })
        .filter(f => f);

      geoJson = {
        type: 'FeatureCollection',
        features,
      }
    } else {
      if (isObject(res)) {
        geoJson = res
      } else {
        let json = ''
        if (res) {
          json = res.replaceAll(/\t/g, '')
          json = json.replaceAll(/\r/g, '')
          json = json.replaceAll(/\n/g, '')
          json = json.replaceAll(/\r\n/g, '')
        }
        geoJson = JSON.parse(json)
      }
    }

    if (geoJson?.features?.length === 0) {
      // Message.warning('暂无数据')
      // 如果没有数据，需要移除已存在的图层
      removeLayer(layerId)
      closeLoading()
      return
    }

    let isMultiPolygon = false

    // 判断该geojson是不是多面
    if (geoJson?.features?.length) {
      const features = geoJson.features
      if (features.length) {
        features.forEach((feature) => {
          if (feature.geometry.type === 'MultiPolygon') {
            isMultiPolygon = true
            const coordinates = feature.geometry.coordinates
            const newCoordinates = []
            coordinates.forEach((coordinate) => {
              if (coordinate.length > 1) {
                coordinate.forEach((item) => {
                  newCoordinates.push([item])
                })
              } else {
                newCoordinates.push(coordinate)
              }
            })
            feature.geometry.coordinates = newCoordinates
          }
        })
      }
    }
    
    // 点图层
    const multiPointFeatures = geoJson.features.filter(f => f.geometry.type === 'MultiPoint')
    
    // console.log('geojson----', geoJson)
    
    // 监听空白区域点击事件清空marker选中状态
    // 移除之前的监听器，避免重复绑定
    map.off('click', clearMarkerClick);
    map.on('click', (e) => {
      const features = map.queryRenderedFeatures(e.point);
      // 延迟一点执行，避免与marker点击事件冲突
      setTimeout(() => {
        clearMarkerClick(features)
      }, 10);
    });

    if (multiPointFeatures.length > 0) {
      removeMarkers(layerId)
      const style = getLayerStyleByPkid(layerId)?.style
      const markers = [];
      // 创建标记并添加点击事件
      multiPointFeatures.forEach(feature => {
        feature.geometry.coordinates.forEach(lngLat => {
          const wrapper = document.createElement('div');
          wrapper.style.display = 'flex';
          wrapper.style.flexDirection = 'column';
          wrapper.style.alignItems = 'center';
          wrapper.style.transform = 'translateY(-42px)'; 
          wrapper.style.marginTop = '12px';

          // 创建圆（圆心对准坐标）
          const circle = document.createElement('div');
          circle.style.width = '20px';
          circle.style.height = '20px';
          circle.style.backgroundColor = style?.paint?.['circle-color'] || '#00BAFF';
          circle.style.borderRadius = '50%';
          circle.style.border = `${style?.paint?.['circle-stroke-width'] || 2}px solid ${style?.paint?.['circle-stroke-color'] || '#fff'}`;

          // 创建 label（显示在圆下方，但不影响圆对齐）
          const label = document.createElement('div');
          label.innerText = feature.properties?.name || '';
          label.style.marginTop = '4px';
          label.style.fontSize = '12px';
          label.style.color = '#333';
          label.style.fontWeight = 'bold';
          label.style.whiteSpace = 'nowrap';
          label.style.pointerEvents = 'none';

          wrapper.appendChild(circle);
          wrapper.appendChild(label);

          const marker = new mapboxgl.Marker(wrapper).setLngLat(lngLat).addTo(map);

      
          // 点击逻辑
          marker.getElement().addEventListener('click', (e) => {
            // 阻止事件冒泡，避免触发地图点击事件
            e.stopPropagation();
            
            if (activeMarker) {
              const oldCircle = activeMarker.getElement().querySelector('div:first-child');
              // 恢复为原始背景色
              const oldOriginalColor = activeMarker.getElement().getAttribute('data-original-color') || '#00BAFF';
              if (oldCircle) {
                oldCircle.style.backgroundColor = oldOriginalColor;
              }
            }
      
            // 获取当前marker的圆
            const currentCircle = marker.getElement().querySelector('div:first-child');
            
            if (currentCircle) {
              currentCircle.style.backgroundColor = '#007BFF';
            }
      
            activeMarker = marker;
            isMarkerClick = true;
      
            handleMarkerClick(lngLat, feature);
          });
      
          markers.push(marker);
        });
      });
    
      // 将markers存入缓存
      markerCache.set(layerId, markers);
      
      // 调用图层加载完成回调，传递marker信息
      if (typeof onLayerLoaded === 'function') {
        const markerPositions = markers.map(marker => ({
          lngLat: marker.getLngLat()
        }))

        await onLayerLoaded({
          layerId,
          type: 'marker',
          features: markerPositions
        })
        
      }
      closeLoading();
      return;
    } else {
      removeMarkers(layerId)
    }

    if (map.getSource(layerId)) {
      await map.getSource(layerId).setData(geoJson)
    } else {
      await map.addSource(layerId, {
        type: 'geojson',
        data: geoJson,
      })
    }
    if (!map.getLayer(layerId)) {
      await map.addLayer({
        id: layerId,
        source: layerId,
        ...getLayerStyle(layerId),
      })
      
      // 应用样式配置（如果存在）
      const styleConfig = getLayerStyleByPkid(layerId)
      if (styleConfig) {
        setTimeout(() => {
          applyLayerStyle(map, layerId, layerId)
        }, 100) // 延迟一点确保图层已添加
      }
      
      await layerManager.addLayer(layerId,'', true, 1, [])
    }
    
    addLabelLayer(geoJson, layerId)

    // 调用图层加载完成回调，传递GeoJSON数据
    if (typeof onLayerLoaded === 'function' && geoJson.features && geoJson.features.length > 0) {
      // 检测图层类型
      let layerType = 'polygon'
      const firstFeature = geoJson.features[0]
      if (firstFeature.geometry) {
        const geometryType = firstFeature.geometry.type
        if (geometryType === 'LineString' || geometryType === 'MultiLineString') {
          layerType = 'line'
        } else if (geometryType === 'Point') {
          layerType = 'point'
        }
      }
      
      onLayerLoaded({
        layerId,
        type: layerType,
        features: geoJson.features
      })
    }
    
    closeLoading()
  }

  const handleMarkerClick = (lngLat, feature) => {
    if (typeof onMarkerClick === 'function') {
      onMarkerClick(lngLat, feature)
    }
  }

  const clearMarkerClick = (features) => {
    if (!isMarkerClick && activeMarker && features.length === 0) {
      const circle = activeMarker.getElement().querySelector('div:first-child');
      // 恢复为原始背景色
      const originalColor = activeMarker.getElement().getAttribute('data-original-color') || '#00BAFF';
      if (circle) {
        circle.style.backgroundColor = originalColor;
      }
      activeMarker = null; 
    }

    isMarkerClick = false
  }

  const removeMarkers = (layerId) => {
    const markers = markerCache.get(layerId);
    
    // 遍历标记并删除它们
    if (markers && markers.length > 0) {
      markers.forEach((marker) => {
        marker.remove(); 
      });
      markerCache.delete(layerId); 
    }
  };

  const addLabelLayer = (geoJson, layerId) => {
    const labelFeatures = [];
  
    geoJson.features.forEach(f => {
      try {
        const props = {
          name: f.properties.name || '',
          ...f.properties
        };
  
        const type = f.geometry.type;
  
        if (type === 'Point') {
          labelFeatures.push({
            type: 'Feature',
            geometry: f.geometry,
            properties: props
          });
  
        } else if (type === 'MultiPoint') {
          f.geometry.coordinates.forEach(coord => {
            if (Array.isArray(coord) && coord.length >= 2) {
              labelFeatures.push({
                type: 'Feature',
                geometry: {
                  type: 'Point',
                  coordinates: coord
                },
                properties: props
              });
            }
          });
  
        } else if (type === 'LineString') {
          const mid = turf.midpoint(
            turf.point(f.geometry.coordinates[0]),
            turf.point(f.geometry.coordinates[f.geometry.coordinates.length - 1])
          );
          mid.properties = props;
          labelFeatures.push(mid);
  
        } else if (type === 'MultiLineString') {
          f.geometry.coordinates.forEach(line => {
            if (line.length >= 2) {
              const mid = turf.midpoint(
                turf.point(line[0]),
                turf.point(line[line.length - 1])
              );
              mid.properties = props;
              labelFeatures.push(mid);
            }
          });
  
        } else if (type === 'Polygon') {
          const centroid = turf.centroid(f);
          centroid.properties = props;
          labelFeatures.push(centroid);
  
        } else if (type === 'MultiPolygon') {
          f.geometry.coordinates.forEach(polygon => {
            const poly = {
              type: 'Polygon',
              coordinates: polygon
            };
            const centroid = turf.centroid(poly);
            centroid.properties = props;
            labelFeatures.push(centroid);
          });
  
        }
      } catch (e) {
        console.warn('Error processing feature', e);
      }
    });
  
    const labelGeoJson = {
      type: 'FeatureCollection',
      features: labelFeatures
    };
  
    const labelSourceId = `${layerId}-labels`;
  
    if (map.getSource(labelSourceId)) {
      map.getSource(labelSourceId).setData(labelGeoJson);
    } else {
      map.addSource(labelSourceId, {
        type: 'geojson',
        data: labelGeoJson
      });
  
      map.addLayer({
        id: labelSourceId,
        type: 'symbol',
        source: labelSourceId,
        layout: {
          'text-field': ['get', 'name'],
          'text-size': 14,
          'text-anchor': 'center',
          'text-justify': 'center',
          'text-offset': [0, 0],
          'text-allow-overlap': true,
          'visibility': 'visible'
        },
        paint: {
          'text-color': '#333',
          'text-halo-color': '#fff',
          'text-halo-width': 1.5,
          'text-halo-blur': 0.5
        },
        minzoom: 14
      });
    }
  };


  const removeLayer = (layerId) => {
    // 清理marker缓存和地图上的markers
    if (markerCache.has(layerId)) {
      const markers = markerCache.get(layerId)
      markers.forEach(marker => {
        // 确保完全移除marker
        marker.remove()
      })
      markerCache.delete(layerId)
      
      // 重置活跃marker状态
      if (activeMarker) {
        activeMarker = null
      }
    }

    if (map.getLayer(layerId)) {
      map.removeLayer(layerId)
      layerManager.removeLayer(layerId)
    }
    if (map.getSource(layerId)) {
      map.removeSource(layerId)
    }
    // 同时移除 label 图层和数据源
    const labelLayerId = `${layerId}-labels`;
    if (map.getLayer(labelLayerId)) {
      map.removeLayer(labelLayerId);
    }
    if (map.getSource(labelLayerId)) {
      map.removeSource(labelLayerId);
    }
    // 移除点高亮图层
    if (map.getLayer(`${layerId}-points`)) {
      map.removeLayer(`${layerId}-points`);
    }
  }

  const resetSource = () => {
    layerSource = {}
    buildingLayerCache.clear()
    markerCache.clear()
  }

  if (typeof window !== 'undefined') {
    emitter.on('HIGHLIGHT_GEOJSON', (geojson) => {
      if (!map) return;
      // 先移除旧的
      if (map.getLayer(highlightGeoJsonLayerId)) {
        map.removeLayer(highlightGeoJsonLayerId);
      }
      if (map.getSource(highlightGeoJsonLayerId)) {
        map.removeSource(highlightGeoJsonLayerId);
      }
      map.addSource(highlightGeoJsonLayerId, {
        type: 'geojson',
        data: geojson
      });
      map.addLayer({
        id: highlightGeoJsonLayerId,
        type: 'fill',
        source: highlightGeoJsonLayerId,
        paint: {
          'fill-color': '#ff0',
          'fill-opacity': 0.4,
          'fill-outline-color': '#ff9900'
        }
      });
    });
    emitter.on('LOCATE_TO_GEOJSON', (geojson) => {
      if (!map) return;
      // 计算所有坐标的包围盒中心
      let coords = [];
      if (geojson && geojson.geometry.coordinates.length) {
        coords = geojson.geometry.coordinates[0][0][0]
      }
      map.flyTo({ center: coords, duration: 1000 });
    });
    emitter.on('CLEAR_HIGHLIGHT_GEOJSON', () => {
      if (!map) return;
      if (map.getLayer(highlightGeoJsonLayerId)) {
        map.removeLayer(highlightGeoJsonLayerId);
      }
      if (map.getSource(highlightGeoJsonLayerId)) {
        map.removeSource(highlightGeoJsonLayerId);
      }
    });
    emitter.on('HIGHLIGHT_MARKERS', (coords) => {
      if (!map) return;
      // 先清除旧的
      if (highlightMarkerList.length) {
        highlightMarkerList.forEach(marker => marker.remove());
        highlightMarkerList = [];
      }
      const lngLat = coords[0]
      if (Array.isArray(coords) && coords.length) {
        coords.forEach(lngLat => {
          const wrapper = document.createElement('div');
          wrapper.style.display = 'flex';
          wrapper.style.flexDirection = 'column';
          wrapper.style.alignItems = 'center';
          wrapper.style.transform = 'translateY(-42px)'; // 上移
          // wrapper.style.marginTop = '-12px';
          
          // const el = document.createElement('div');
          const center = document.createElement('div');
          center.style.width = '20px';
          center.style.height = '20px';
          center.style.backgroundColor = '#FF0000'; // 选中颜色
          center.style.borderRadius = '50%';
          center.style.border = '2px solid white';
          
          // el.style.width = '84px';
          // el.style.height = '84px';
          // el.style.background = 'rgba(255, 0, 0, 0.5)'; // 选中颜色
          // el.style.borderRadius = '50%';
          // el.style.display = 'flex';
          // el.style.justifyContent = 'center';
          // el.style.alignItems = 'center';
          wrapper.appendChild(center);
          const marker = new mapboxgl.Marker(wrapper).setLngLat(lngLat).addTo(map);
          highlightMarkerList.push(marker);
        });
      }

      map.flyTo({ center: lngLat, duration: 1000 });
    });
    emitter.on('CLEAR_HIGHLIGHT_MARKERS', () => {
      if (highlightMarkerList.length) {
        highlightMarkerList.forEach(marker => marker.remove());
        highlightMarkerList = [];
      }
    });
    
    // 监听隐藏匹配 markers 的事件
    emitter.on('HIDE_MATCHING_MARKERS', (showExistingMarkerCoords) => {
      if (!map || !Array.isArray(showExistingMarkerCoords)) return;
      
      console.log('收到隐藏匹配 markers 事件，坐标:', showExistingMarkerCoords);
      
      // 遍历所有缓存的 markers
      markerCache.forEach((markers, layerId) => {
        markers.forEach(marker => {
          const markerLngLat = marker.getLngLat();
          const markerCoords = [markerLngLat.lng, markerLngLat.lat];
          
          // 检查是否与 showExistingData 的坐标匹配
          const isMatched = showExistingMarkerCoords.some(existingCoords => {
            const tolerance = 0.0001; // 容差值
            return Math.abs(markerCoords[0] - existingCoords[0]) < tolerance &&
                   Math.abs(markerCoords[1] - existingCoords[1]) < tolerance;
          });
          
          if (isMatched) {
            console.log('找到匹配的 multiPointFeatures marker，将隐藏:', markerCoords);
            // 隐藏匹配的 marker
            marker.getElement().style.display = 'none';
          }
        });
      });
    });
    
    // 监听恢复隐藏 markers 的事件
    emitter.on('RESTORE_HIDDEN_MARKERS', () => {
      if (!map) return;
      
      console.log('收到恢复隐藏 markers 事件');
      
      // 遍历所有缓存的 markers，恢复显示
      markerCache.forEach((markers, layerId) => {
        markers.forEach(marker => {
          marker.getElement().style.display = '';
        });
      });
    });
  }

  /**
   * 动态更新图层样式
   * @param {string} layerId - 图层ID
   * @param {string} pkid - 样式配置ID
   */
  const updateLayerStyle = (layerId, pkid) => {
    if (map && map.getLayer(layerId)) {
      applyLayerStyle(map, layerId, pkid)
    }
  }

  /**
   * 获取图层当前使用的样式配置
   * @param {string} layerId - 图层ID
   * @returns {object|null} 样式配置对象
   */
  const getLayerCurrentStyle = (layerId) => {
    return getLayerStyleByPkid(layerId)
  }

  return {
    init,
    addLayerByCatalogId,
    removeLayerByCatalogId,
    resetSource,
    setBuildingCallback,
    setBuildingRemovedCallback,
    setMarkerClickCallback,
    setLayerLoadedCallback,
    getBuildingCache: () => buildingLayerCache,
    updateLayerStyle, // 新增
    getLayerCurrentStyle, // 新增
  }
}
